package com.jthinker.service.impl;

import com.jthinker.bean.vo.QueryResult;
import com.jthinker.bean.vo.SearchFilter;
import com.jthinker.bean.vo.UserInfo;
import com.jthinker.dao.UserDao;
import com.jthinker.service.RoleService;
import com.jthinker.service.UserService;
import org.apache.commons.collections.MapUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.Serializable;
import java.util.Map;
import java.util.Set;

/**
 */
@Service
public class UserServiceImpl implements UserService
{
    @Resource
    private UserDao userDao;

    @Resource
    private RoleService roleService;

    @Override
    public UserInfo login(String username, String saltPassword)
    {
        Map<String, Object> record = userDao.login(username, saltPassword);
        if (MapUtils.isEmpty(record))
        {
            return null;
        }

        UserInfo info = new UserInfo();
        info.setId(MapUtils.getLong(record, "id"));
        info.setUsername(MapUtils.getString(record, "username"));
        info.setNickname(MapUtils.getString(record, "nickname"));
        return info;
    }

    @Override
    public void updatePass(String saltpass, Serializable id)
    {
        userDao.updatePass(saltpass, id);
    }

    @Override
    public boolean isUnique(String username)
    {
        return userDao.isUnique(username);
    }

    @Override
    public void createUser(Map<String, Object> record)
    {
        String username = MapUtils.getString(record, "username");
        String password = MapUtils.getString(record, "password");
        //        String salt = PasswordUtils.getSalt();
        //        String newPassword = PasswordUtils.encryptPassword(username, password, salt);

        //        record.put("salt", salt);
        //        record.put("password", newPassword);

        userDao.createUser(record);
    }

    @Override
    public Map<String, Object> findByUsername(String username)
    {
        return userDao.findOneByUsername(username);
    }

    @Override
    public Set<String> findRoles(String username)
    {
        //        Map<String, Object> user = findByUsername(username);
        //        List<Long> roleIds = user.getArrayLong("role_ids");
        //        return roleService.findRoles(roleIds.toArray(new Long[0]));
        return null;
    }

    @Override
    public Set<String> findPermissions(String username)
    {
        //        Map<String, Object> user = findByUsername(username);
        //        if (user == null)
        //        {
        //            return Collections.EMPTY_SET;
        //        }
        //        return roleService.findRoles(user.getArrayLong("role_ids").toArray(new Long[0]));

        return null;
    }

    @Override
    public QueryResult<Map<String, Object>> query(SearchFilter filter)
    {
        return userDao.query(filter);
    }
}
